<?php
declare (strict_types = 1);

namespace app\api\controller\Order;

use app\BaseController;
use app\common\model\Product\Cart as CartModel;
use app\common\model\User\User as UserModel;
use app\common\model\User\Address as AddressModel;
use think\exception\ValidateException;

class Order extends BaseController
{

    // 订单列表
    public function index()
    {
        //
    }

    // 新增订单
    public function add() {
        /*
            order => 新增一个订单 （创建model,validate）
            order_product => 新增一个订单商品记录  （创建model,validate）
            product => 库存减去下单库存  （更新数据的操作）
            user => 扣除下单积分  （更新数据的操作）
            user_record => 新增购物记录  （新增数据的操作）
            cart => 下单成功后购物车里的相关数据删除  （删除数据的操作）
        */

        try {
            $userid = $this->request->param('userid');

            // 购物车id
            $CartIds = $this->request->param('cartid');

            $addrid = $this->request->param('addrid');

            $content = $this->request->param('content');

            $CartIdArr = !empty($CartIds) ? explode(',',$CartIds) : [];

            $User = UserModel::find($userid);

            if(!$User) {
                throw new \Exception("用户不存在");
                
            }

            $address = AddressModel::where(['userid' => $userid,'id' => $addrid])->find();

            if(!$address) {
                throw new \Exception("收货地址不存在");
            }

            $CartList = CartModel::withJoin(['product'])->whereIn('cart.id',$CartIds)->select();

            // 订单总价变量
            $total = 0;

            foreach ($CartList as $key => $item) {
                if(!in_array($item['id'],$CartIdArr)) {
                    throw new \Exception("购物车的某个商品不存在，请重新选择");
                    
                }

                // 库存判断
                if($item['nums'] > $item['product']['stock']) {
                    throw new \Exception("{$item['product']['name']}库存不足", );
                    
                } 

                $point = bcsub((String)$User['point'],(String)$item['total']);

                if($point < 0) {
                    throw new \Exception("积分不足，请及时充值");
                    
                }

                $total += $item['total'];

            }

            // 订单数据
            $OrderData = [
                'userid' => $userid,
                'addrid' => $addrid,
                'code' => build_code('ASK'),
                'total' => $total,
            ];

        } catch (ValidateException $th) {
            //throw $th;
        } catch (\Exception $error) {
            $this->error($error->getMessage());
        }
    }
}
